package library;

/***
 * @author Ragnvald Fuglestein
 */

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import baseStructure.Artist;
import baseStructure.Log;
import baseStructure.SortedList;

public class SerializedLibraryBackend extends LibraryBackend {
	private File file;
	
	public SerializedLibraryBackend(File file) {
		super();
		this.file = file;
	}
	
	public String toString() { return this.file.getAbsolutePath(); }

	//TODO FIX THIS TOO!
	@Override public void readAll() throws IOException {
		if (!file.exists()) return;
		FileInputStream filestream = null;
		ObjectInputStream objectstream = null;
		SortedList<Artist> list;
		
		try {
			filestream = new FileInputStream(file);
			objectstream = new ObjectInputStream(filestream);
			list = (SortedList<Artist>) objectstream.readObject();
			objectstream.close();
			filestream.close();
		} catch (IOException | ClassNotFoundException e) {
			try {
				if (filestream != null) filestream.close();
			} catch (IOException e1) { }
			throw new IOException(e);
		}

		Log.i(String.format("Loaded library from " + file.getAbsolutePath()));
		setList(list);
	}

	//TODO FIX!
	@Override public void writeAll(SortedList<Artist> list) throws IOException {
		FileOutputStream filestream = null;
		ObjectOutputStream objectstream = null;
		try {
			filestream = new FileOutputStream(file);
			objectstream = new ObjectOutputStream(filestream);
			objectstream.writeObject(list);
			objectstream.close();
			filestream.close();
		} catch (IOException e) {
			try {
				if (filestream != null) filestream.close();
			} catch (IOException e1) { }
			throw e;
		}
		
		clearList();
		Log.i(String.format("Saved library to " + file.getAbsolutePath()));
		//throw new ExportException("Error writing to: " + file.getAbsolutePath());
	}

	@Override public SortedList<Artist> getAll() {
		
		return getList();
	}

}
